package gupaoedu.LazySingleton;

import java.io.Serializable;

/**
 * gupaoedu.LazySingleton
 * linwenjie
 * 2019-06-19
 * 懒汉内部类单例模式
 */
public class LazyInnerSingleton implements Serializable {
    //防止通过反射破坏单例
    private LazyInnerSingleton(){
        if(innerSingletonHolder.Lazy != null){
            throw new RuntimeException("不允许创建多个实例");
        }
    }

    public static final LazyInnerSingleton getInstance(){
        return innerSingletonHolder.Lazy;
    }

    //默认不会执行，只有被调用时，才会初始化
    private static class  innerSingletonHolder{
        public static final LazyInnerSingleton Lazy = new LazyInnerSingleton();
    }

    //防止序列化破坏单例
    private Object readResolve(){
        return innerSingletonHolder.Lazy;
    }
}
